<template>
  <div class="classify">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-alert
          title="注意:只允许为第三级分类设置相关的参数"
          type="warning"
          show-icon
        >
        </el-alert>
      </div>
      <el-row>
        <span class="cascader-title">选择商品分类:</span>
        <el-cascader
          v-model="value"
          :options="options"
          :props="props"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many"> </el-tab-pane>
        <el-tab-pane label="静态参数" name="only"> </el-tab-pane>
        <div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            style="width:180px;"
            :disabled="value.length !== 3"
            @click="openDailog('create')"
          >
            {{ activeName === 'many' ? '添加参数' : '添加属性' }}
          </el-button>
          <el-table
            :data="activeName === 'many' ? manyTableData : onlyTableData"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(tag, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(i, row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  clearable
                  style="width:180px;"
                  v-if="row.inputVisible"
                  @keyup.enter.native="addTagInputBlur(row)"
                  v-model="row.inputValue"
                  size="small"
                  ref="addTagInputRef"
                  @blur="addTagInputBlur(row)"
                >
                </el-input>
                <el-button
                  v-else
                  size="small"
                  icon="el-icon-plus"
                  @click="showTagInput(row)"
                  >新增标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column label="分类参数 ID" prop="attr_id">
            </el-table-column>
            <el-table-column
              :label="activeName === 'many' ? '参数名称' : '属性名称'"
              prop="attr_name"
            >
            </el-table-column>
            <el-table-column label="操作" v-slot="{ row }">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="clickOperation(row, 'edit')"
              >
                操作
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="clickOperation(row, 'del')"
              >
                删除
              </el-button>
            </el-table-column>
          </el-table>
        </div>
      </el-tabs>
    </el-card>
    <!-- 修改和添加的对话框 -->
    <el-dialog
      :title="
        (type === 'create' ? '添加' : '修改') +
          (activeName === 'many' ? '参数' : '属性')
      "
      :visible.sync="dialogVisible"
      width="50%"
      :append-to-body="true"
    >
      <el-form
        :model="submitForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态参数'"
          prop="attr_name"
        >
          <el-input clearable v-model="submitForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDailog">取 消</el-button>
        <el-button type="primary" @click="submitAttrNameForm()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getGoodCategories,
  getGoodCateList,
  updateGoodCategories,
  addCategories,
  deleteCategories
} from '@/api/goods'
export default {
  name: 'Classify',
  components: {},
  data() {
    return {
      submitForm: {
        attr_name: ''
      },
      value: [],
      options: [],
      activeName: 'many',
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      oldTab: 'many',
      type: '', // create 添加  edit 编辑
      manyTableData: [], // 动态参数
      onlyTableData: [], // 静态参数
      dialogVisible: false, // 对话框
      rules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    deleteTag(i, item) {
      item.attr_vals.splice(i, 1)
      this.updateGoodCategories(item)
    },
    showTagInput(item) {
      item.inputVisible = true
    },
    // 新增标签失去焦点 或 回车键
    addTagInputBlur(item) {
      if (item.inputValue.trim().length === 0) {
        item.inputValue = ''
        item.inputVisible = false
        return
      }
      item.attr_vals.push(item.inputValue.trim())
      item.inputValue = ''
      item.inputVisible = false
      this.updateGoodCategories(item)
    },
    updateGoodCategories(item) {
      updateGoodCategories({
        id: item.cat_id,
        attrId: item.attr_id,
        data: {
          attr_name: item.attr_name,
          attr_sel: this.activeName,
          attr_vals: item.attr_vals.join(' ')
        }
      }).then(() => {
        this.closeDailog()
      })
    },
    closeDailog() {
      if (this.type === 'create') {
        this.submitForm.attr_name = ''
      }
      this.type = ''
      this.dialogVisible = false
    },
    openDailog(type) {
      this.type = type
      this.dialogVisible = true
    },
    // 提交表单
    submitAttrNameForm() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写参数名称')
        }
        if (this.type === 'create') {
          const params = {
            id: this.value[2],
            data: {
              attr_name: this.submitForm.attr_name,
              attr_sel: this.activeName
            }
          }
          addCategories(params).then(() => {
            this.getGoodCateList()
            this.closeDailog()
          })
        } else if (this.type === 'edit') {
          this.updateGoodCategories(this.submitForm)
        }
      })
    },
    // 操作按钮
    clickOperation(item, type) {
      if (type === 'edit') {
        this.submitForm = item
        this.openDailog(type)
      } else if (type === 'del') {
        this.$confirm('该操作将永久删除该数据,是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCategories({
            id: this.value[2],
            attrid: item.attr_id
          }).then(() => {
            this.getGoodCateList()
          })
        })
      }
    },
    async getGoodCategories() {
      const { data: res } = await getGoodCategories()
      this.options = res
    },
    handleChange() {
      // 级联选择器发生变化时触发
      this.getGoodCateList()
    },
    handleClick() {
      // tab 发生变化时触发
      const { activeName, oldTab, options } = this
      if (activeName === oldTab && options.length > 0) return
      this.getGoodCateList()
    },
    // 获取参数列表
    async getGoodCateList() {
      const { activeName, value } = this
      if (value.length !== 3) {
        this.value = []
        return this.$message.error('只允许为第三级分类设置相关的参数')
      }
      const { data: res } = await getGoodCateList({
        id: value[2],
        sel: activeName
      })
      res.forEach(v => {
        v.attr_vals = v.attr_vals ? v.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        v.inputVisible = false
        // 文本框中输入的值
        v.inputValue = ''
      })
      if (activeName === 'many') {
        this.manyTableData = res
      } else {
        this.onlyTableData = res
      }
      this.oldTab = activeName
    }
  },
  created() {
    this.getGoodCategories()
  }
}
</script>
<style lang="scss" scoped>
.cascader-title {
  margin-right: 20px;
}
.el-cascader {
  width: 400px;
}
.el-tabs {
  margin-top: 20px;
  .el-table {
    margin-top: 20px;
    .el-tag {
      margin-right: 20px;
    }
  }
}
</style>
